<?php
	session_start();
	if ($_SESSION['logd'] != 1){
	    Header("Location:login.php");
	}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Message Hub</title>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>

<body>

   <!-- Begin Wrapper -->
   <div id="wrapper">
   
         <!-- Begin Header -->
         <div id="header">
			<?php
				include("include/header.html");
			?>	
		 </div>
		 <!-- End Header -->
		 
         <!-- Begin Faux Columns -->
		 <div id="faux">
		 
		       <!-- Begin Left Column -->
		       <div id="leftcolumn">
				<?php
					include("include/menu.php");
				?>
		       </div>
		       <!-- End Left Column -->
		 
		       <!-- Begin Right Column -->
		       <div id="rightcolumn">
<?php
	//include("include/toTwitter.php");
	require_once('scripts/Message.php');
	require_once('scripts/twitter/TwitterMessage.php');

	// This is needed for email:
	require_once('scripts/mail/phpMailer_v2.1.0beta1/class.phpmailer.php');
	require_once('scripts/mail/phpMailer_v2.1.0beta1/class.smtp.php');


        //we check if the user is logged in. If that is not the case, we will forward him to admin.php so he can login. The exacd procedure of the test is explained in board.php
        //session_start();
        //if ($_SESSION['logd'] != 1){
        //        Header("Location:login.php");
        //} else {
		if (($_POST['receiver'] != "")&&($_POST['title'] != "")){

			include("scripts/dbconnect.php");
			//@ $db = mysqli_connect("localhost","root","gibbiX12345","msghub");
			//$link = mysql_connect("127.0.0.1","root","gibbiX12345","msghub");

			//preparing variables
			if (!get_magic_quotes_gpc()){
				$title = addslashes(strip_tags($_POST['title']));
				$receiver = addslashes(strip_tags($_POST['receiver']));
				$sender = $_SESSION['PeId'];
				$tags = explode(",", $_POST['tags']);
				if ($_POST['text'] != ""){
					$text = addslashes(strip_tags($_POST['text']));
				} else {
					$text = "no text";
				}
				//$twittermessage = toTwitter($sender, $title, $text);
				//$twitter = addslashes($twittermessage);
			}

			//writing data to database
			$mainquery = "INSERT INTO Messages (SenderPeId, ReceiverPeId, Message, Title) VALUES ('".$sender."', '".$receiver."', '".$text."', '".$title."')";
			$db->query($mainquery);
			$msgid = mysqli_insert_id($db);

			//we won't write them to the database, because you can always recreate the shorten message...
			//$twitterquery = "INSERT INTO SpecificMessages (MsgId, Message) VALUES ('".$msgid."', '".$twitter."')";
			//$db->query($twitterquery);
			//$twitid = mysqli_insert_id($db);
			//echo $twittermessage;

			//writing tags
			foreach ($tags as $tag1){

				$tag = trim($tag1);
				$tag = strtolower($tag);
				$checkquery = "SELECT Tag FROM TagNames WHERE Tag = '".$tag."'";
				$checkexec = $db->query($checkquery);
				$checkrow = $checkexec->fetch_assoc();

				if (($checkrow['Tag'] == "")&&($tag != "")){
					$insertquery = "INSERT INTO TagNames (Tag) VALUES ('".$tag."')";
					$db->query($insertquery);
				} 

				$inserttagquery = "INSERT INTO Tags (MsgId, TaNaId) VALUES ('".$msgid."', (SELECT TaNaId FROM TagNames WHERE Tag = '".$tag."'))";
				$db->query($inserttagquery);
			}

			/*
			 * Sending Email.
			 * This part is not finished! It's just a demo for School!
			 * Will be cleaned up later!
			 */
			//====================================================================

			//Get data
			//$mailQuery			= "SELECT * FROM Email WHERE PeId = '".$receiver."';";
			$mailQuery			= "SELECT Person.Username, Email.EmailAdress FROM Person LEFT JOIN Email ON Person.PeId = Email.PeId WHERE Person.PeId = '".$receiver."';";
			$mailExec			= $db->query($mailQuery);
			//$mailRow			= $mailExec->fetch_assoc();

			$mail				= new PHPMailer();
			$mail->IsSMTP();
			$mail->SMTPAuth			= true;
			$mail->SMTPSecure		= "ssl";
			$mail->Host			= "smtp.gmail.com";
			$mail->Port			= 465;

			$mail->Username			= "";
			$mail->Password			= "";

			$mail->From			= "";
			$mail->FromName			= "MessageHub";
			$mail->Subject			= $title;
			$mail->Body			= $text;
			$mail->AltBody			= "Alt Body";

			$mail->WordWrap			= 50;

			while($mailRow = mysqli_fetch_array($mailExec)){
				$mail->AddAddress($mailRow['EmailAdress'], $mailRow['Username']);
			}

			$mail->AddReplyTo("","Msghub");

			$mail->IsHTML(true);
			
			if(!$mail->Send()){
			    	echo "Error! Mail not send on Error: ".$mail->ErrorInfo."<br />";
			} else {
			    	echo "Message has been sent succesfully <br />";
			}


			//====================================================================

			// send Tweet
			//echo "sending Tweet now! <br />";
			//echo $receiver."<br />";
			$query				= "SELECT * FROM Twitter WHERE PeId = '".$receiver."';";
			//echo $query."<br />";
			$exec				= $db->query($query);
			//echo "query executed! <br />";
			$row				= $exec->fetch_assoc();

			if ($row['TwId']!=""){
			    	//echo "in if! <br />";
			    	$twitter		= new TwitterMessage($msgid);
				$twitter->sendMessage();
				//echo "Tweet sent! <br />";
			}

			//TODO Add sendmail. Maybe in the way of sendmail($title, $text, $receiver);

		} else {
			echo "Please enter at least a receiver and a title!";
		}
	//}
?>
			   <div class="clear"></div>
			   
		       </div>
		       <!-- End Right Column -->
			   
			   <div class="clear"></div>
			   
         </div>	   
         <!-- End Faux Columns --> 

         <!-- Begin Footer -->
         <div id="footer">
			<?php
				include("include/footer.html");
			?>		
         </div>
		 <!-- End Footer -->
		 
   </div>
   <!-- End Wrapper -->
</body>
</html>
